﻿using System;
using System.Web;
using System.Collections.Specialized;
using System.Net;
using System.IO;
using System.Text;
namespace WeiBeeCommon.Core
{
    public class OAuthSohu : OAuthBase
    {
        public OAuthSohu()
        {
            Title = @"搜狐微博";
            LinkIconUrl = @"http://open.t.sohu.com/upload/connect_button-04134430.png";
            ConsumerKey = "AYByrZSXj5uaFKytTomy";
            ConsumerSecret = "kSIld=0ET$nUtRsWjUr(tl2-Q1l#C0G04Rr3cdgn";
            OauthCallback = "null";
            RequestToken = "http://api.t.sohu.com/oauth/request_token";
            Authorize = "http://api.t.sohu.com/oauth/authorize";//?hd=default";
            AccessToken = "http://api.t.sohu.com/oauth/access_token";
        }

        protected override void MultipartformBody(NameValueCollection qs, byte[] boundarybytes, byte[] boundarybytes1, Stream requestStream, string formdataTemplate)
        {
            requestStream.Write(boundarybytes1, 0, boundarybytes1.Length);
            string key = "status";
            string formitem = string.Format(formdataTemplate, key, Utility.UrlEncode(qs[key]));
            byte[] formitembytes = Encoding.UTF8.GetBytes(formitem);
            requestStream.Write(formitembytes, 0, formitembytes.Length);
            requestStream.Write(boundarybytes, 0, boundarybytes.Length);
        }

        public const string XAuthUsernameKey = "x_auth_username";
        public const string XAuthPasswordKey = "x_auth_password";
        public const string XClientAuthKey = "x_auth_mode";
        public void AddXAuthParameters(string username, string password)
        {
            base.AdditionalParameters.Add(new QueryParameter(XAuthUsernameKey, Utility.UrlEncode(username)));
            base.AdditionalParameters.Add(new QueryParameter(XAuthPasswordKey, Utility.UrlEncode(password)));
            base.AdditionalParameters.Add(new QueryParameter(XClientAuthKey, "client_auth"));
        }
        public override void XAuthLogin(string username, string password)
        {
            SetCallbackUrl(string.Empty);
            AddXAuthParameters(username, password);
            string response = OAuthWebRequest(Method.POST, AccessToken, string.Empty);
            if (response.Length > 0)
            {
                NameValueCollection qs = HttpUtility.ParseQueryString(response);
                GetTokenAndTokenSecret(qs);
            }
        }
    }
}
